package com.cn.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.pojo.FileInfo;
import com.cn.pojo.UserInfo;
import com.cn.service.DownloadService;
import com.cn.service.FileService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class DownloadController {
	@Autowired
	@Qualifier("fileService")
	FileService fileService;
	
	@Autowired
	@Qualifier("downloadService")
	DownloadService downloadService;
	@RequestMapping(value="/downloadFileById.do")
	public ResponseEntity<byte[]> downloadFile(Integer j,HttpServletRequest request) throws IOException {
		request.setCharacterEncoding("UTF-8");
		FileInfo fileInfo=fileService.consultFileById(j);
		HttpSession session=request.getSession();
		UserInfo user =new UserInfo();
		user=(UserInfo)session.getAttribute("user");
		String path=request.getServletContext().getRealPath("/");
		File file=new File(path+File.separator+fileInfo.getUrl());
		HttpHeaders headers=new HttpHeaders();
		String fileName=URLEncoder.encode(fileInfo.getFileName(),"UTF-8");
		headers.setContentDispositionFormData("attachment",fileName );
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		fileService.updateDownLoadSum(j);
		downloadService.insertInfo(j, user.getId());
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
	}
	@RequestMapping(value="/consultDetail.do")
	public void consultDetail(HttpServletRequest request,HttpServletResponse response,ObjectMapper mapper) throws IOException {
		request.setCharacterEncoding("UTF-8");
		List<Map<String,Object>> detial=downloadService.detail();
		String json=mapper.writeValueAsString(detial);
		response.getWriter().print(json);
		response.getWriter().flush();
		response.getWriter().close();
	}
}
